package bm73;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/9/5 23:02
 * BM73. 最长回文子串
 * https://www.nowcoder.com/practice/b4525d1d84934cf280439aeecc36f4af?tpId=295&tqId=25269&ru=%2Fpractice%2Ff33f5adc55f444baa0e0ca87ad8a6aac&qru=%2Fta%2Fformat-top101%2Fquestion-ranking&sourceUrl=%2Fexam%2Foj
 */
public class Solution {

    // 动态规划思路
    public int getLongestPalindrome01 (String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        int n = s.length();
        int maxLen = 0;
        boolean[][] dp = new boolean[n][n]; // dp[i][j] 表示 [i, j]区间字符串 s 是否为回文串
        // 构造 dp 表 根据 dp 表找到最大长度
        for (int i = n - 1; i >= 0; i--) {
            for (int j = 0; j < n; j++) {
                if (s.charAt(i) == s.charAt(j)) {
                    dp[i][j] = i + 1 < j ? dp[i + 1][j - 1] : true;
                }
                if (dp[i][j] && j - i + 1 > maxLen) {
                    maxLen = j - i + 1;
                }
            }
        }
        return maxLen;
    }

    // 中心扩散法
    public int getLongestPalindrome02 (String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        // 依次将 s 的每个位置作为中心点进行扩散, 求得最大的回文长度
        int n = s.length();
        int maxLen = 1;
        // 回文串长度为奇数的情况
        for (int center = 0; center < n; center++) {
            int left = center, right = center;
            while (left >= 0 && right < n) {
                if (s.charAt(left) != s.charAt(right)) {
                    break;
                }
                --left;
                ++right;
            }
            maxLen = Math.max(maxLen, right - 1 - (left + 1) + 1);
        }
        // 回文串的长度为偶数的情况, 此时中间点为两个
        for (int center = 0; center < n - 1; center++) {
            int left = center, right = center + 1;
            while (left >= 0 && right < n) {
                if (s.charAt(left) != s.charAt(right)) {
                    break;
                }
                --left;
                ++right;
            }
            maxLen = Math.max(maxLen, right - 1 - (left + 1) + 1);
        }
        return maxLen;
    }
}
